package com.huhao.smark;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import org.json.JSONObject;

import java.io.IOException;

import static com.huhao.smark.Config.*;

public class LoginActivity extends AppCompatActivity {

    private EditText accountEditText;
    private EditText passwordEditText;
    private Button loginButton;
    private TextView registerTextView;
    private CheckBox termsCheckBox;
    private static final String BASE_URL = HTTP + IP + PORT + LOGIN_API;

    private OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        // 初始化视图
        accountEditText = findViewById(R.id.account_edit_text);
        passwordEditText = findViewById(R.id.password_edit_text);
        loginButton = findViewById(R.id.login_button);
        registerTextView = findViewById(R.id.register_text_view);
        termsCheckBox = findViewById(R.id.terms_check_box);
        // 设置登录按钮点击事件
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoginClick();
            }
        });

        // 设置注册文本点击事件
        registerTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到注册页面
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 重置登录表单
        accountEditText.setText("");
        passwordEditText.setText("");
        termsCheckBox.setChecked(false);
    }

    private void onLoginClick() {
        String account = accountEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();

        // 简单验证
        if (account.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!termsCheckBox.isChecked()) {
            Toast.makeText(this, "请阅读并同意用户协议和隐私政策", Toast.LENGTH_SHORT).show();
            return;
        }

        // 发送登录请求
        sendLoginRequest(account, password);
    }

    private void sendLoginRequest(String account, String password) {
        // 创建JSON请求体
        JSONObject requestBodyJson = new JSONObject();
        try {
            requestBodyJson.put("account", account);
            requestBodyJson.put("password", password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置请求头和请求体
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.Companion.create(requestBodyJson.toString(), mediaType);

        // 创建请求
        Request request = new Request.Builder()
                .url(BASE_URL)
                .post(body)
                .build();

        // 发起请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "网络请求失败，请检查网络连接", Toast.LENGTH_SHORT).show();
                        Log.e("LoginActivity", "Request failed: ", e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        // 解析响应体
                        JSONObject jsonResponse = new JSONObject(responseBody);

                        int code = jsonResponse.optInt("code", -1);
                        boolean success = jsonResponse.optBoolean("success", false);
                        String message = jsonResponse.optString("message", "未知错误");

                        if (success && code == 200) {
                            // 登录成功
                            JSONObject data = jsonResponse.optJSONObject("data");
                            String token = data.optString("token");
                            JSONObject user = data.optJSONObject("user");
                            String account = user.optString("account");
                            String username = user.optString("username");
                            String avatar = user.optString("avatar");
                            int bookCount = user.optInt("bookCount");
                            int id = user.optInt("id");
                            // 使用 SharedPreferences 存储登录状态和token
                            SharedPreferences sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();

                            editor.putBoolean("isLoggedIn", true);
                            editor.putString("token", token);
                            editor.putString("account", account);
                            editor.putString("username", username);
                            editor.putInt("bookCount", bookCount);
                            editor.putInt("id", id);
                            editor.putString("avatar", avatar);

                            Log.i("token", token);
                            editor.apply();

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                    // 登录成功，返回主页
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            });
                        } else {
                            // 登录失败
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "登录失败: " + message, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } else {
                    // HTTP错误
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }
}